package com.yonyou.crm.base.attrgroup.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.base.attrgroup.entity.AttrRelationVO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.common.rowstate.constant.RowStateConstant;

@Service
public class AttrRelationBizServiceImpl extends BaseBizServiceImpl<AttrRelationVO> {

	@Autowired
	private AttrGroupBizServiceImpl agService;
	
	/**
	 * 批量新增
	 * @param attrGroupId
	 * @param voList
	 */
	public void batchInsert(Long attrGroupId, List<AttrRelationVO> voList) {
				
		if (voList ==null || voList.size() == 0) {
			return;
		}
		
		if (attrGroupId != null) {
			
			for (AttrRelationVO vo : voList) {
				vo.setAttrGroupId(attrGroupId);
			}
		}

		dao.saveSql(AttrRelationVO.class, "batchInsert", voList);
	}
	
	/**
	 * 批量修改
	 * @param attrGroupId
	 * @param voList
	 */
	public void batchUpdate(Long attrGroupId, List<AttrRelationVO> voList) {
		
		if (voList == null || voList.size() == 0) {
			return;
		}
		
		List<AttrRelationVO> addList = new ArrayList<AttrRelationVO>();
		List<AttrRelationVO> deleteList = new ArrayList<AttrRelationVO>();
		
		for (AttrRelationVO vo : voList) {
			
			vo.setAttrGroupId(attrGroupId);
			
			switch (vo.getEditState()) {
				case RowStateConstant.ADD:
					addList.add(vo);
					break;
				case RowStateConstant.DELETE:
					deleteList.add(vo);
					break;
				default:
					break;
			}
		}
		
		//校验删除的属性值是否被产品引用
		List<Map<String, Object>> citedList = agService.getAGByProductOrPrdtype(new String[]{attrGroupId.toString()});
		if (citedList.size() > 0) {
			throw new CrmBusinessException("属性组被产品或产品分类引用，属性或属性值不可移除！");
		}
		
		batchInsert(null, addList);
		batchDelete(deleteList);
	}
	
	/**
	 * 根据属性组id批量删除
	 * @param ids
	 */
	public void batchDelete(String[] ids) {
		super.batchDeleteByIDs(AttrRelationVO.class, ids);
	}
	
	/**
	 * 批量删除
	 * @param voList
	 */
	private void batchDelete(List<AttrRelationVO> voList) {
		
		if (voList == null || voList.size() == 0) {
			return;
		}
		
		dao.deleteSql(AttrRelationVO.class, "batchDelete", voList);
	}
}
